"use strict";
/* Controllers */
app.controller("userGroupRoleController", ['$scope', '$location', '$rootScope', '$q', '$routeParams', 'userGroupRoleService', 'userGroupService', function ($scope, $location, $rootScope, $q, $routeParams, userGroupRoleService, userGroupService) {

    var vm = $scope.vm = {};
    vm.p = {};
    var routeId = $routeParams.id;

    $scope.getRole = function () {
        var vm = $scope.vm;
        var params = {
            id: routeId
        };
        var procFn = function (res) {
            console.log("get_role")
            if (res.success && res.data) {
                vm.p = res.data
                console.log("add_tags_input")
                // $('#userGroupIds').tagsinput('add', vm.p.userGroupIds);
                // $('#userIds').tagsinput('add', vm.p.userIds);
            } else {
                alert(res.msg);
            }
        };
        return userGroupRoleService.getRole(params, procFn, errorFn);
    };

    var substringMatcher = function (strs) {
        return function findMatches(q, cb) {
            var matches, substringRegex;

            // an array that will be populated with substring matches
            matches = [];

            // regex used to determine if a string contains the substring `q`
            var substrRegex = new RegExp(q, 'i');

            // iterate through the pool of strings and for any string that
            // contains the substring `q`, add it to the `matches` array
            $.each(strs, function (i, str) {
                if (substrRegex.test(str)) {
                    matches.push(str);
                }
            });

            cb(matches);
        };
    };

    var substringMatcherObj = function (dataObjs, toMatchKey) {
        return function findMatches(q, cb) {
            var matches, substringRegex;

            // an array that will be populated with substring matches
            matches = [];

            // regex used to determine if a string contains the substring `q`
            var substrRegex = new RegExp(q, 'i');

            // iterate through the pool of strings and for any string that
            // contains the substring `q`, add it to the `matches` array
            $.each(dataObjs, function (i, dataObj) {
                if (substrRegex.test(dataObj[toMatchKey])) {
                    matches.push(dataObj);
                }
            });

            cb(matches);
        };
    };

    var initSugUserGroupIds = function () {
        var vm = $scope.vm;
        var params = {};
        var procFn = function (response) {
            console.log('listUserGroup')
            var data = response.data;
            if (data == null) return;

            $('#userGroupIds').tagsinput({
                itemValue: 'id',
                itemText: 'userGroupName',
                typeaheadjs: [{
                    minLength: 0
                }, {
                    name: 'userGroupName',
                    displayKey: 'userGroupName',
                    source: substringMatcherObj(data, "userGroupName"),
                    limit: 20
                }],
                freeInput: false
            });

            if (typeof (vm.p.userGroupIds) == 'undefined' || vm.p.userGroupIds == '') {
                return
            }
            var userGroupIdsArr = vm.p.userGroupIds.split(',')
            userGroupIdsArr.forEach(function (x) {
                var ugiLabel = data.find(function (y) {
                    return y.id.toString() == x
                })
                if (typeof (ugiLabel) != 'undefined') {
                    $('#userGroupIds').tagsinput('add', ugiLabel)
                }
            })

        };

        return userGroupService.listUserGroup(params, procFn, errorFn);
    }

    var initSugUserIds = function () {
        var vm = $scope.vm;
        var params = {};
        var procFn = function (response) {
            console.log('listUser')
            var data = response.data;
            if (data == null) return;
            var ugn = data.map(function (x) {
                return x.userName
            })

            $('#userIds').tagsinput({
                typeaheadjs: [{
                    minLength: 0
                }, {
                    name: 'ugiSource',
                    source: substringMatcher(ugn),
                }],
                freeInput: false
            });
        };
        return userGroupRoleService.listUser(params, procFn, errorFn);
    }

    var initSugPermissionIds = function () {
        var vm = $scope.vm;
        var params = {};
        var procFn = function (response) {
            console.log('initSugPermissionIds')
            var data = response.data;
            if (data == null) return;

            var fls = data.map(function (x) {
                return x.functionLabel
            })

            $('#functionLabels').tagsinput({
                typeaheadjs: [{
                    minLength: 0
                }, {
                    name: 'ugiSource',
                    source: substringMatcher(fls),
                }],
                freeInput: true
            });

            if (typeof (vm.p.functionLabels) == 'undefined' || vm.p.functionLabels == '') {
                return
            }

        };

        return userGroupRoleService.listPermission(params, procFn, errorFn);
    }

    function getNewObjectOf(src) {
        return Object.assign({}, src);
    }

    //e_time\s*[\)]?\s*[>|>=|<|<=|=]{1,2}\s*['|"]{1}%s['|"]{1}
    var errorFn = function (result) {
        alert(result);
    };

    $scope.roleSave = function () {
        var vm = $scope.vm;
        var params = vm.p;
        var procFn = function (response) {
            if (response.success && response.data) {
                alert("保存成功！")
            } else {
                alert(response.msg);
            }
        };
        return userGroupRoleService.roleSave(params, procFn, errorFn);
    };


    if (typeof (routeId) != "undefined" && routeId != null) {
        $q.all([$scope.getRole()]).then(function () {
            initSugUserGroupIds()
            initSugUserIds()
            initSugPermissionIds()
        })
    } else {
        initSugUserGroupIds()
        initSugUserIds()
        initSugPermissionIds()
    }

}]);


/* Services */
app.service('userGroupRoleService', ['ajaxService', function (ajaxService) {

    this.roleSave = function (params, successFunction, errorFunction) {
        return ajaxService.AjaxPost(params, "/star/api/basic-service/v1/role/setRole.do", successFunction, errorFunction);
    };

    this.getRole = function (params, successFunction, errorFunction) {
        return ajaxService.AjaxPost(params, "/star/api/basic-service/v1/role/detail.do", successFunction, errorFunction);
    };

    this.listUser = function (params, successFunction, errorFunction) {
        return ajaxService.AjaxPost(params, "/star/api/basic-service/v1/user/user_list.do", successFunction, errorFunction);
    };

    this.listPermission = function (params, successFunction, errorFunction) {
        ajaxService.AjaxPost(params, "/star/api/basic-service/v1/permission/listPermission.do", successFunction, errorFunction);
    };

}]);

